#!/bin/bash

# 检查是否提供了JAR包名称
if [ $# -eq 0 ]; then
    echo "Usage: $0 <jar-file>"
    exit 1
fi

JAR_FILE="$1"
BACKUP_DIR="/opt/vos/backups"  # 备份目录
JAVA_OPTS="-Xms512m -Xmx1024m"  # JVM参数

# 创建备份目录（如果不存在）
mkdir -p "$BACKUP_DIR"

# 备份JAR包（保留原文件名）
if [ -f "$JAR_FILE" ]; then
    echo "正在备份JAR包..."
    cp -f "$JAR_FILE" "$BACKUP_DIR/"
    echo "备份完成: $BACKUP_DIR/$JAR_FILE"
fi

# 杀死现有进程
PID=$(ps -ef | grep java | grep "$JAR_FILE" | grep -v grep | awk '{print $2}')
if [ -n "$PID" ]; then
    echo "正在停止现有进程 (PID: $PID)..."
    kill -9 "$PID"
    sleep 2
fi

# 启动新进程
echo "正在启动应用..."
nohup java $JAVA_OPTS -jar "$JAR_FILE" > nohup.out 2>&1 &

# 显示进度条
echo "启动中..."
for i in {1..20}; do
    percentage=$((i * 5))
    printf "\r[%-20s] %d%%" $(printf "#%.0s" $(seq 1 $i)) $percentage
    sleep 0.2
done
printf "\n启动完成！\n"

# 显示新进程信息
NEW_PID=$(ps -ef | grep java | grep "$JAR_FILE" | grep -v grep | awk '{print $2}')
if [ -n "$NEW_PID" ]; then
    echo "应用已启动，PID: $NEW_PID"
else
    echo "警告：未能检测到应用进程，请检查日志"
fi